<template>
  <view class="patrol-monitor-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="header-title">巡检监控</view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <!-- 日期选择 -->
      <view class="filter-item">
        <view class="filter-label">日期</view>
        <view class="date-selector" @click="showDatePicker = true">
          <text class="date-text">{{ formatDate(selectedDate) }}</text>
          <image src="/static/icons/calendar-icon.svg" class="calendar-icon"></image>
        </view>
      </view>

      <!-- 监控类型切换 -->
      <view class="monitor-tabs">
        <view 
          v-for="(tab, index) in monitorTabs" 
          :key="index"
          class="tab-item"
          :class="{ active: activeTab === index }"
          @click="switchTab(index)"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>

    <!-- 巡检员监控 -->
    <view v-if="activeTab === 0" class="inspector-monitor">
      <!-- 统计卡片 -->
      <view class="stats-cards">
        <view class="stats-card">
          <view class="card-title">总巡检员</view>
          <view class="card-value">{{ inspectorStats.totalInspectors }}人</view>
        </view>
        <view class="stats-card">
          <view class="card-title">在岗巡检员</view>
          <view class="card-value">{{ inspectorStats.activeInspectors }}人</view>
        </view>
        <view class="stats-card">
          <view class="card-title">平均小票打印率</view>
          <view class="card-value">{{ formatPercent(inspectorStats.avgTicketPrintRate) }}</view>
        </view>
        <view class="stats-card">
          <view class="card-title">平均丢单缴费率</view>
          <view class="card-value">{{ formatPercent(inspectorStats.avgMissedOrderPaymentRate) }}</view>
        </view>
      </view>

      <!-- 巡检员列表 -->
      <view class="inspector-list">
        <view class="list-header">
          <text class="header-cell name">巡检员</text>
          <text class="header-cell">小票打印</text>
          <text class="header-cell">丢单缴费率</text>
          <text class="header-cell">状态</text>
        </view>
        
        <view v-for="(inspector, index) in inspectorList" :key="index" class="list-item" @click="viewInspectorDetail(inspector)">
          <view class="item-cell name">
            <view class="inspector-info">
              <view class="inspector-name">{{ inspector.name }}</view>
              <view class="inspector-id">ID: {{ inspector.id }}</view>
            </view>
          </view>
          <view class="item-cell">
            <view class="print-info">
              <text class="print-count">{{ inspector.ticketPrinted }}/{{ inspector.totalTickets }}</text>
              <text class="print-rate">{{ formatPercent(inspector.ticketPrintRate) }}</text>
            </view>
          </view>
          <view class="item-cell">
            <text class="payment-rate" :class="getRateClass(inspector.missedOrderPaymentRate)">
              {{ formatPercent(inspector.missedOrderPaymentRate) }}
            </text>
          </view>
          <view class="item-cell">
            <view class="status-badge" :class="inspector.status">
              {{ getStatusText(inspector.status) }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 道路监控 -->
    <view v-if="activeTab === 1" class="road-monitor">
      <!-- 统计卡片 -->
      <view class="stats-cards">
        <view class="stats-card">
          <view class="card-title">监控道路</view>
          <view class="card-value">{{ roadStats.totalRoads }}条</view>
        </view>
        <view class="stats-card">
          <view class="card-title">异常道路</view>
          <view class="card-value">{{ roadStats.abnormalRoads }}条</view>
        </view>
        <view class="stats-card">
          <view class="card-title">总丢单数</view>
          <view class="card-value">{{ roadStats.totalMissedOrders }}单</view>
        </view>
        <view class="stats-card">
          <view class="card-title">总未建单数</view>
          <view class="card-value">{{ roadStats.totalUnbuiltOrders }}单</view>
        </view>
      </view>

      <!-- 道路列表 -->
      <view class="road-list">
        <view class="list-header">
          <text class="header-cell name">道路名称</text>
          <text class="header-cell">丢单数</text>
          <text class="header-cell">未建单数</text>
          <text class="header-cell">状态</text>
        </view>
        
        <view v-for="(road, index) in roadList" :key="index" class="list-item" @click="viewRoadDetail(road)">
          <view class="item-cell name">
            <view class="road-info">
              <view class="road-name">{{ road.name }}</view>
              <view class="road-code">编码: {{ road.code }}</view>
            </view>
          </view>
          <view class="item-cell">
            <text class="missed-count" :class="getMissedOrderClass(road.missedOrders)">
              {{ road.missedOrders }}
            </text>
          </view>
          <view class="item-cell">
            <text class="unbuilt-count" :class="getUnbuiltOrderClass(road.unbuiltOrders)">
              {{ road.unbuiltOrders }}
            </text>
          </view>
          <view class="item-cell">
            <view class="status-badge" :class="road.status">
              {{ getRoadStatusText(road.status) }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期选择弹窗 -->
    <up-datetime-picker
      ref="datetimePicker"
      v-model="showDatePicker"
      mode="date"
      :value="selectedDate"
      @confirm="onDateConfirm"
      @cancel="showDatePicker = false"
    ></up-datetime-picker>

    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ detailTitle }}</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body">
          <view v-if="detailType === 'inspector'" class="inspector-detail">
            <view class="detail-item">
              <text class="detail-label">巡检员姓名：</text>
              <text class="detail-value">{{ currentDetail.name }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">巡检员ID：</text>
              <text class="detail-value">{{ currentDetail.id }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">小票打印情况：</text>
              <text class="detail-value">{{ currentDetail.ticketPrinted }}/{{ currentDetail.totalTickets }} ({{ formatPercent(currentDetail.ticketPrintRate) }})</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">丢单缴费率：</text>
              <text class="detail-value">{{ formatPercent(currentDetail.missedOrderPaymentRate) }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">工作状态：</text>
              <text class="detail-value">{{ getStatusText(currentDetail.status) }}</text>
            </view>
          </view>
          
          <view v-if="detailType === 'road'" class="road-detail">
            <view class="detail-item">
              <text class="detail-label">道路名称：</text>
              <text class="detail-value">{{ currentDetail.name }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">道路编码：</text>
              <text class="detail-value">{{ currentDetail.code }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">丢单数量：</text>
              <text class="detail-value">{{ currentDetail.missedOrders }}单</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">未建单数量：</text>
              <text class="detail-value">{{ currentDetail.unbuiltOrders }}单</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">道路状态：</text>
              <text class="detail-value">{{ getRoadStatusText(currentDetail.status) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 响应式数据
const selectedDate = ref(new Date())
const showDatePicker = ref(false)
const activeTab = ref(0)
const showDetailModal = ref(false)
const detailType = ref('')
const detailTitle = ref('')
const currentDetail = ref(null)

// 监控类型标签
const monitorTabs = ref([
  { name: '巡检员监控', value: 'inspector' },
  { name: '道路监控', value: 'road' }
])

// 巡检员统计数据
const inspectorStats = ref({
  totalInspectors: 0,
  activeInspectors: 0,
  avgTicketPrintRate: 0,
  avgMissedOrderPaymentRate: 0
})

// 道路统计数据
const roadStats = ref({
  totalRoads: 0,
  abnormalRoads: 0,
  totalMissedOrders: 0,
  totalUnbuiltOrders: 0
})

// 巡检员列表
const inspectorList = ref([])

// 道路列表
const roadList = ref([])

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化百分比
const formatPercent = (rate) => {
  return `${rate.toFixed(2)}%`
}

// 切换标签
const switchTab = (index) => {
  activeTab.value = index
  if (index === 0) {
    loadInspectorData()
  } else {
    loadRoadData()
  }
}

// 日期确认
const onDateConfirm = (value) => {
  selectedDate.value = new Date(value)
  showDatePicker.value = false
  if (activeTab.value === 0) {
    loadInspectorData()
  } else {
    loadRoadData()
  }
}

// 获取费率等级样式
const getRateClass = (rate) => {
  if (rate >= 90) return 'excellent'
  if (rate >= 80) return 'good'
  if (rate >= 70) return 'normal'
  return 'poor'
}

// 获取丢单数量样式
const getMissedOrderClass = (count) => {
  if (count === 0) return 'excellent'
  if (count <= 5) return 'good'
  if (count <= 10) return 'normal'
  return 'poor'
}

// 获取未建单数量样式
const getUnbuiltOrderClass = (count) => {
  if (count === 0) return 'excellent'
  if (count <= 3) return 'good'
  if (count <= 8) return 'normal'
  return 'poor'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'active': '在岗',
    'offline': '离岗',
    'break': '休息'
  }
  return statusMap[status] || '未知'
}

// 获取道路状态文本
const getRoadStatusText = (status) => {
  const statusMap = {
    'normal': '正常',
    'warning': '警告',
    'abnormal': '异常'
  }
  return statusMap[status] || '未知'
}

// 查看巡检员详情
const viewInspectorDetail = (inspector) => {
  currentDetail.value = inspector
  detailType.value = 'inspector'
  detailTitle.value = `${inspector.name} - 详细信息`
  showDetailModal.value = true
}

// 查看道路详情
const viewRoadDetail = (road) => {
  currentDetail.value = road
  detailType.value = 'road'
  detailTitle.value = `${road.name} - 详细信息`
  showDetailModal.value = true
}

// 加载巡检员数据
const loadInspectorData = () => {
  // 模拟巡检员数据
  const inspectors = [
    { id: 'INS001', name: '张三', status: 'active' },
    { id: 'INS002', name: '李四', status: 'active' },
    { id: 'INS003', name: '王五', status: 'offline' },
    { id: 'INS004', name: '赵六', status: 'active' },
    { id: 'INS005', name: '钱七', status: 'break' },
    { id: 'INS006', name: '孙八', status: 'active' }
  ]

  inspectorList.value = inspectors.map(inspector => {
    const totalTickets = Math.floor(Math.random() * 50) + 20 // 20-70张
    const ticketPrinted = Math.floor(totalTickets * (0.7 + Math.random() * 0.3)) // 70%-100%
    const ticketPrintRate = (ticketPrinted / totalTickets) * 100
    const missedOrderPaymentRate = Math.random() * 30 + 70 // 70%-100%
    
    return {
      ...inspector,
      totalTickets,
      ticketPrinted,
      ticketPrintRate,
      missedOrderPaymentRate
    }
  })

  // 计算统计数据
  const activeInspectors = inspectorList.value.filter(i => i.status === 'active').length
  const avgTicketPrintRate = inspectorList.value.reduce((sum, i) => sum + i.ticketPrintRate, 0) / inspectorList.value.length
  const avgMissedOrderPaymentRate = inspectorList.value.reduce((sum, i) => sum + i.missedOrderPaymentRate, 0) / inspectorList.value.length

  inspectorStats.value = {
    totalInspectors: inspectorList.value.length,
    activeInspectors,
    avgTicketPrintRate,
    avgMissedOrderPaymentRate
  }
}

// 加载道路数据
const loadRoadData = () => {
  // 模拟道路数据
  const roads = [
    { code: 'RD001', name: '中山路', status: 'normal' },
    { code: 'RD002', name: '解放路', status: 'warning' },
    { code: 'RD003', name: '人民路', status: 'normal' },
    { code: 'RD004', name: '建设路', status: 'abnormal' },
    { code: 'RD005', name: '文化路', status: 'normal' },
    { code: 'RD006', name: '商业街', status: 'warning' },
    { code: 'RD007', name: '学府路', status: 'normal' },
    { code: 'RD008', name: '工业路', status: 'abnormal' }
  ]

  roadList.value = roads.map(road => {
    const missedOrders = Math.floor(Math.random() * 15) // 0-15单
    const unbuiltOrders = Math.floor(Math.random() * 10) // 0-10单
    
    return {
      ...road,
      missedOrders,
      unbuiltOrders
    }
  })

  // 计算统计数据
  const abnormalRoads = roadList.value.filter(r => r.status === 'abnormal' || r.status === 'warning').length
  const totalMissedOrders = roadList.value.reduce((sum, r) => sum + r.missedOrders, 0)
  const totalUnbuiltOrders = roadList.value.reduce((sum, r) => sum + r.unbuiltOrders, 0)

  roadStats.value = {
    totalRoads: roadList.value.length,
    abnormalRoads,
    totalMissedOrders,
    totalUnbuiltOrders
  }
}

// 页面加载
onMounted(() => {
  loadInspectorData()
})
</script>

<style lang="scss" scoped>
.patrol-monitor-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background-color: white;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-item {
    margin-bottom: 30rpx;
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 15rpx;
      font-weight: 500;
    }
    
    .date-selector {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 12rpx;
      background-color: #fafafa;
      
      .date-text {
        font-size: 32rpx;
        color: #333;
      }
      
      .calendar-icon {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  
  .monitor-tabs {
    display: flex;
    background-color: #f0f0f0;
    border-radius: 12rpx;
    padding: 6rpx;
    
    .tab-item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      font-size: 28rpx;
      color: #666;
      border-radius: 8rpx;
      transition: all 0.3s;
      
      &.active {
        background-color: white;
        color: #667eea;
        font-weight: bold;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.stats-cards {
  display: flex;
  flex-wrap: wrap;
  padding: 0 20rpx;
  margin-bottom: 30rpx;
  
  .stats-card {
    width: calc(50% - 20rpx);
    margin: 10rpx;
    background-color: white;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .card-title {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 15rpx;
      text-align: center;
    }
    
    .card-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
    }
  }
}

.inspector-list, .road-list {
  background-color: white;
  margin: 0 20rpx 30rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .list-header {
    display: flex;
    background-color: #f8f9fa;
    padding: 25rpx 20rpx;
    border-bottom: 2rpx solid #e9ecef;
    
    .header-cell {
      flex: 1;
      font-size: 28rpx;
      font-weight: bold;
      color: #495057;
      text-align: center;
      
      &.name {
        flex: 1.5;
        text-align: left;
      }
    }
  }
  
  .list-item {
    display: flex;
    padding: 25rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    transition: background-color 0.2s;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:active {
      background-color: #f8f9fa;
    }
    
    .item-cell {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      
      &.name {
        flex: 1.5;
        justify-content: flex-start;
      }
    }
  }
}

.inspector-info, .road-info {
  .inspector-name, .road-name {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 5rpx;
  }
  
  .inspector-id, .road-code {
    font-size: 24rpx;
    color: #666;
  }
}

.print-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .print-count {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 5rpx;
  }
  
  .print-rate {
    font-size: 24rpx;
    color: #666;
  }
}

.payment-rate, .missed-count, .unbuilt-count {
  font-weight: bold;
  
  &.excellent {
    color: #28a745;
  }
  
  &.good {
    color: #17a2b8;
  }
  
  &.normal {
    color: #ffc107;
  }
  
  &.poor {
    color: #dc3545;
  }
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
  
  &.active {
    background-color: #d4edda;
    color: #155724;
  }
  
  &.offline {
    background-color: #f8d7da;
    color: #721c24;
  }
  
  &.break {
    background-color: #fff3cd;
    color: #856404;
  }
  
  &.normal {
    background-color: #d4edda;
    color: #155724;
  }
  
  &.warning {
    background-color: #fff3cd;
    color: #856404;
  }
  
  &.abnormal {
    background-color: #f8d7da;
    color: #721c24;
  }
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  
  .detail-content {
    background-color: white;
    border-radius: 20rpx;
    width: 90%;
    max-width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
    
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #f0f0f0;
      
      .detail-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        font-size: 40rpx;
        color: #999;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .detail-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .detail-item {
        display: flex;
        margin-bottom: 25rpx;
        
        .detail-label {
          font-size: 28rpx;
          color: #666;
          width: 200rpx;
          flex-shrink: 0;
        }
        
        .detail-value {
          font-size: 28rpx;
          color: #333;
          flex: 1;
        }
      }
    }
  }
}
</style>